package com.zhengshang.web.controller.system;

import com.zhengshang.admin.security.service.TokenService;
import com.zhengshang.api.domain.AppBalanceRecord;
import com.zhengshang.api.domain.AppPhoneArea;
import com.zhengshang.api.mapper.AppBalanceRecordMapper;
import com.zhengshang.api.service.IAppPhoneAreaService;
import com.zhengshang.common.annotation.Log;
import com.zhengshang.common.constant.UserConstants;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.core.controller.BaseController;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.entity.SysRole;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.core.domain.model.LoginUser;
import com.zhengshang.common.core.page.TableDataInfo;
import com.zhengshang.common.enums.BusinessType;
import com.zhengshang.common.enums.UserStatus;
import com.zhengshang.common.utils.*;
import com.zhengshang.common.utils.poi.ExcelUtil;
import com.zhengshang.system.mapper.SysUserMapper;
import com.zhengshang.system.service.ISysPostService;
import com.zhengshang.system.service.ISysRoleService;
import com.zhengshang.system.service.ISysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.Size;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IAppPhoneAreaService phoneAreaService;


    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "{user.log.title}", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public AjaxResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, MessageUtils.message("user.export"));
    }

    @Log(title = "{user.log.title}", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel(MessageUtils.message("user.export"));
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "{user.log.title}", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error(MessageUtils.message("user.add.username.exists", user.getUserName()));
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error(MessageUtils.message("user.add.phone.exists", user.getUserName()));
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error(MessageUtils.message("user.add.email.exists", user.getUserName()));
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUserType(UserConstants.USER_TYPE_SYS);
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "{user.log.title}", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error(MessageUtils.message("user.edit.phone.exists", user.getUserName()));
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error(MessageUtils.message("user.edit.email.exists", user.getUserName()));
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "{user.log.title}", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "{user.log.title}", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "{user.log.title}", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    @GetMapping("/treeUserlist/{userIds}")
    public TableDataInfo treeUserlist(SysUser user, @PathVariable Long[] userIds) {
        startPage();
        List<SysUser> list = userService.selectUserList(user, userIds);
        return getDataTable(list);
    }

    /**
     * 获取用户列表（会员列表）
     */
    @PreAuthorize("@ss.hasPermi('system:appUser:memberList')")
    @GetMapping("/memberList")
    public TableDataInfo memberList(SysUser user) {
        user.setUserType(UserConstants.USER_TYPE_APP);
        startPage();
        List<SysUser> list = userService.memberList(user);
        list.forEach(sysUser -> {
           String phonenumber = sysUser.getPhonenumber();
            AppPhoneArea appPhoneArea = phoneAreaService.queryByPhone(phonenumber);
            if(StringUtils.isNotNull(appPhoneArea)){
                sysUser.setPhoneArea(appPhoneArea.getPhoneArea()+"|"+appPhoneArea.getPhoneNewIsp());
            }
        });
        return getDataTable(list);
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:appUser:edit')")
    @Log(title = "{user.log.title}", businessType = BusinessType.UPDATE)
    @PutMapping("/changeAppUserStatus")
    public AjaxResult changeAppUserStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        int result = userService.updateUserStatus(user);
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            //如果是停用，禁止账号继续操作
            String tokenKey = tokenService.getValue(tokenService.getAppUserIdKey(user.getUserId()));
            tokenService.delLoginAppUser(tokenKey, user.getUserId());
        }
        return toAjax(result);
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:appUser:resetPwd')")
    @Log(title = "{user.log.title}", businessType = BusinessType.UPDATE)
    @PutMapping("/resetAppPwd")
    public AjaxResult resetAppPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 修改所属合伙人
     */
    @PutMapping("/changePartner")
    public AjaxResult changePartner(@RequestBody SysUser user) {
        return toAjax(userService.changePartner(user));
    }

    /**
     * 更新贡献值
     */
    @PutMapping("/updateContributionValue")
    public AjaxResult updateContributionValue(@RequestBody SysUser user) {
        return toAjax(userService.updateContributionValue(user));
    }

    /**
     * 开通合伙人
     */
    @PreAuthorize("@ss.hasPermi('system:appUser:edit')")
    @PostMapping("/openingPartner")
    public AjaxResult openingPartner(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        user.setPartainOpeningTime(DateUtils.getNowDate());
        return toAjax(userService.openingPartner(user));
    }

    @Log(title = "{user.log.title}", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/exportMember")
    public AjaxResult exportMember(SysUser user) {
        user.setUserType(UserConstants.USER_TYPE_APP);
        List<SysUser> list = userService.memberList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "会员数据");
    }

}
